import 'package:HnXG/Api.dart';
import 'package:HnXG/snackbar.dart';
import 'package:flutter/material.dart';

class QueuePage extends StatefulWidget {
  const QueuePage({super.key});

  @override
  State<StatefulWidget> createState() => _QueueStatePage();
}

class _QueueStatePage extends State<QueuePage> {
Future<Map<String, dynamic>>? _taskInfoData;  // 新增数据请求变量
    @override
  void initState() {
    super.initState();
    _taskInfoData = Api.GetView_TaskOrderInfo();  // 初始化时获取数据
 
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
        title: const Text('队列',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            shadows: [Shadow(color: Colors.black38, offset: Offset(1,1), blurRadius: 3)],
          )
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Colors.blue.shade700, Colors.lightBlue.shade400],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
          ),
        ),
        centerTitle: true,
        elevation: 4,
        automaticallyImplyLeading: false,
      ),
      body: FutureBuilder(
        future: _taskInfoData,
       
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snapshot.hasError) {
            return Center(child: Text('加载失败: ${snapshot.error}'));
          }
          if (!snapshot.hasData || snapshot.data!['dto'] .isEmpty) {
            return const Center(child: Text('暂无队列'));
          
          }
  
          return ListView.builder(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            itemCount: snapshot.data!['dto'].length,
            itemBuilder: (context, index) => Column(
              children: [
                Container(
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey[300]!),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  margin: const EdgeInsets.symmetric(vertical: 4),
                  child: ListTile(
                    title: Text('用户队列${index+1}',style: TextStyle(fontSize: 15),),
                    subtitle: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                         Text('类型: ${snapshot.data!['dto'][index]['type']}'),
                        Text('起始地点: ${snapshot.data!['dto'][index]['startName']}'),
                        Text('目标地点: ${snapshot.data!['dto'][index]['endName']}'),
                        Text('优先级: ${snapshot.data!['dto'][index]['counter']}'),
                        Text('创建日期: ${snapshot.data!['dto'][index]['createTime']}'),
                          Text('队列Id: ${snapshot.data!['dto'][index]['taskInfo_id']}',style: TextStyle(fontSize: 12),),
                        const SizedBox(height: 8),
                        ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.red.shade400,
                            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8)
                          ),
                          onPressed: () async {
                            try {
                            
                            
                              final result = await Api.DeleteTaskInfo(
                               snapshot.data!['dto'][index]['taskInfo_id']
                              );
                              if (result['state'] == true) {
                                setState(() {
                                SuccessSnackBar.show(context, message: result ["msg"]);
                                  _taskInfoData = Api.GetView_TaskOrderInfo();
                                });
                              }else{
                                ErrorSnackBar.show(context, message: result ["msg"]); 
                                // 添加setState触发界面刷新
                                setState(() {
                                  _taskInfoData = Api.GetView_TaskOrderInfo();
                                });
                              }
                            } catch (e) {
                              print('删除失败: $e');
                            }
                          },
                          child: const Text('取消队列', style: TextStyle(color: Colors.white)),
                        )
                      ],
                    ),
                  ),
                ),
                const Divider(height: 1, color: Colors.grey),
              ],
            ),
          );
        },
      ),
    );
  }

}